import java.util.Arrays;

public class TestHeap {//创建大根堆
    int[] elem;
    int usedsize;
    public TestHeap(){
        this.elem=new int[10];
    }
    public void initElem(int[] array){
        for(int i=0;i<array.length;i++){
            this.elem[i]=array[i];
            usedsize++;
        }
    }
    public void createHeap(){
        for(int parent=(usedsize-1-1)/2;parent>=0;parent--){
            siftDown(parent,usedsize);
        }
    }

    public void siftDown(int parent,int usedsize){
        int child=2*parent+1;
        //至少有左孩子
        while(child<usedsize){
            if(child+1<usedsize&&elem[child]<elem[child+1]){
                child++;
                //child下标对应的值一定是左右孩子最大值
            }
            if(elem[child]>elem[parent]){
                swap(elem,parent,child);
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }
    }
    public void swap(int[] array,int i,int j){
        int tem=array[i];
        array[i]=array[j];
        array[j]=tem;
    }
    //堆的插入
    public void offer(int val){
        if(isFulled()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedsize]=val;
        siftUp(usedsize);
        usedsize++;
    }
    public void siftUp(int child){
        int parent=(child-1)/2;
        while(parent>=0){
            if(elem[child]>elem[parent]){
                swap(elem,parent,child);
            }else{
                break;
            }
        }
    }
    private boolean isFulled(){
        return usedsize==elem.length;
    }
    //堆的删除
    public void poll(){
        if(isEmpty()){
            return;
        }
        swap(elem,0,usedsize-1);
        usedsize--;
        siftDown(0,usedsize);
    }

    public boolean isEmpty(){
        return usedsize==0;
    }
}
